package com.longtengyuyun.reentrantLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ZhaoYunLong
 * @date 2022/3/25
 * @description
 */
public class ReentrantLockCondition02 {


    public static void main(String[] args) {
        ReentrantLock reentrantLock1 = new ReentrantLock();
        ReentrantLock reentrantLock2 = new ReentrantLock();

        Thread thread = new Thread(new ThreadTestDemo(reentrantLock1, reentrantLock2));
        Thread thread1 = new Thread(new ThreadTestDemo(reentrantLock2, reentrantLock1));
        thread.start();
        thread1.start();
        thread.interrupt();



    }

    static class ThreadTestDemo implements Runnable{

        ReentrantLock reentrantLock1;
        ReentrantLock reentrantLock2;

        public ThreadTestDemo(ReentrantLock reentrantLock1, ReentrantLock reentrantLock2){
            this.reentrantLock1 = reentrantLock1;
            this.reentrantLock2 = reentrantLock2;
        }

        @Override
        public void run() {
            try {
                if (!reentrantLock1.tryLock()) {
                    TimeUnit.SECONDS.sleep(1000);
                }
                if (!reentrantLock2.tryLock()) {
                    TimeUnit.SECONDS.sleep(1000);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                reentrantLock1.unlock();
                reentrantLock2.unlock();
                System.out.println("执行结束");
            }
        }
    }

    static class ThreadTestDemoTwo implements Runnable{

        ReentrantLock reentrantLock1;
        ReentrantLock reentrantLock2;

        public ThreadTestDemoTwo(ReentrantLock reentrantLock1, ReentrantLock reentrantLock2){
            this.reentrantLock1 = reentrantLock1;
            this.reentrantLock2 = reentrantLock2;
        }

        @Override
        public void run() {
            try {
                if (!reentrantLock1.tryLock()) {
                    TimeUnit.SECONDS.sleep(1000);
                }
                if (!reentrantLock2.tryLock()) {
                    TimeUnit.SECONDS.sleep(1000);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                reentrantLock1.unlock();
                reentrantLock2.unlock();
            }
        }
    }

}
